package com.weilele.leisure.time.leancloud


import android.app.Application
import android.os.Parcelable
import cn.leancloud.*
import com.weilele.mvvm.app
import com.weilele.mvvm.utils.activity.toast
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import kotlinx.parcelize.Parcelize

object AVOSDb {
    init {
        init(app)
    }

    @Parcelize
    data class AppInfo(
        var versionCode: Int,
        var info: String?,
        var url: String?,
        var must: Boolean,
        var webUrl: String?,
    ) : Parcelable

    private fun init(application: Application) {
        // 在 AVOSCloud.initialize() 之前调用
        LeanCloud.setLogLevel(LCLogger.Level.DEBUG)
        // 提供 this、App ID、App Key、Server Host 作为参数
        // 注意这里千万不要调用 cn.leancloud.core.AVOSCloud 的 initialize 方法，否则会出现 NetworkOnMainThread 等错误。
        LeanCloud.initialize(
            application,
            "DX8Eh6xenXVmlLyvHojPWOEe-gzGzoHsz",
            "nMk69t26RImNxmidPOTKhQcv",
            "https://dx8eh6xe.lc-cn-n1-shared.com"
        )
    }

    fun getAppUpdateInfo(info: Function1<AppInfo?, Unit>) {
        val file = LCQuery<LCObject>("App_Info")
        // 将对象保存到云端
        file.firstInBackground.subscribe(object : Observer<LCObject> {
            override fun onSubscribe(disposable: Disposable) {

            }

            override fun onNext(av: LCObject) {
                info.invoke(
                    AppInfo(
                        av.getNumber("version_code").toInt(),
                        av.getString("info"),
                        av.getString("download_url"),
                        av.getBoolean("must_update"),
                        av.getString("download_web"),
                    )
                )
            }

            override fun onError(throwable: Throwable) {
                throwable.message?.toast()
                info.invoke(null)
            }

            override fun onComplete() {

            }
        })
    }
}